package com.liush.bookstore.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.liush.bookstore.mapper.BookMapper;
import com.liush.bookstore.mapper.CartMapper;
import com.liush.bookstore.model.Book;
import com.liush.bookstore.model.Cart;
import com.liush.bookstore.model.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/*
 * 首页控制层
 * */
@Controller
@Slf4j
public class BookController {

    @Autowired
    private BookMapper bookMapper;

    @Autowired
    private CartMapper cartMapper;

    //访问首页面
    @RequestMapping("index")
    public String index(HttpServletRequest request, Model model) {
        //获取登录用户下的购物车商品数量
        User user = (User) request.getSession().getAttribute("user");
        if (user == null || user.equals("")) {
            //用户未登录，默认为0
            model.addAttribute("totalCartCount", "0");
        } else {
            LambdaQueryWrapper<Cart> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Cart::getUser, user.getId());
            List<Cart> carts = cartMapper.selectList(queryWrapper);
            int totalCartCount = 0;
            for (int i = 0; i < carts.size(); i++) {
                Cart cart = carts.get(i);
                totalCartCount += cart.getBuycount();
            }
            model.addAttribute("totalCartCount", totalCartCount);
        }
        return "index.html";
    }

    //异步请求返回json格式的回调内容books
    @ResponseBody
    @RequestMapping("/selectbook/{current}")
    public Page<Book> selectBook(@PathVariable int current) {
        Page<Book> page = new Page<>(current, 4);
        LambdaQueryWrapper<Book> queryWrapper = new LambdaQueryWrapper<>();
        Page<Book> bookPage = bookMapper.selectPage(page, queryWrapper);
        return bookPage;
    }

}
